
package com.x52im.rbchat.logic.chat_group.at;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;

import com.eva.android.widget.BaseActivity;
import com.eva.android.widget.WidgetUtils;
import com.x52im.rbchat.R;
import com.x52im.rbchat.logic.chat_root.AbstractChattingListAdapter;
import com.x52im.rbchat.logic.chat_root.targetchoose.TargetEntity;
import com.x52im.rbchat.logic.chat_root.targetchoose.TargetSource;
import com.x52im.rbchat.logic.chat_root.targetchoose.TargetSourceFilterFactory;
import com.x52im.rbchat.utils.ActivityRequestCode;
import com.x52im.rbchat.utils.IntentFactory;

import java.util.List;

import androidx.core.app.ActivityCompat;

/**
 * "@"功能中对被@对象的管理逻辑进行封装的类。
 *
 * @author JackJiang
 * @since 11.0
 */
public class AtWrapper implements TextWatcher {

    private final static String TAG = AtWrapper.class.getSimpleName();

    private Context context;

    private String gid;

    private AtModel atModel;

    private int curPos;

    private boolean ignoreTextChange = false;

    private AtTextChangeListener listener;

    public AtWrapper(Context context, String gid) {
        this.context = context;
        this.gid = gid;
        atModel = new AtModel();
    }

    public void setTextChangeListener(AtTextChangeListener listener) {
        this.listener = listener;
    }

    public List<String> getAtUsers() {
        return atModel.getAtUsers();
    }

    public void reset() {
        atModel.reset();
        ignoreTextChange = false;
        curPos = 0;
    }

    public void onActivityResult_atTargetSelectedComplete(
            BaseActivity parentActivity, AbstractChattingListAdapter listAdapter, String gid, Intent data){

        if(data != null) {

            //**---- 从选择界面中返回的选中数据
            TargetEntity ue = (TargetEntity) data.getSerializableExtra("selected_user");
            Boolean needInsertAitInText = (Boolean) data.getSerializableExtra("extra_obj");
            if (ue == null || gid == null) {
                Log.w(TAG, "无效的数据！（ue=" + ue + "、gid=" + gid + "）");
                WidgetUtils.showWithDialog(parentActivity, parentActivity.$$(R.string.general_prompt), parentActivity.$$(R.string.general_invalid_data));
                return;
            }

            String targetId = ue.getTargetId();
            String targetName = ue.getTargetName();
//            // uid为"0"当前定义为表示"@所有人"
//            if("0".equals(targetId)) {
//                targetName = "所有人";
//            }

            insertAtUserInner(targetId, targetName, curPos, needInsertAitInText != null ? needInsertAitInText.booleanValue() : false);
        }
    }

    private void insertAtUserInner(String account, String name, int start, boolean needInsertAitInText) {
        name = name + " ";
        String content = needInsertAitInText ? "@" + name : name;
        if (listener != null) {
            // 关闭监听
            ignoreTextChange = true;
            // insert 文本到editText
            listener.onTextAdd(content, start, content.length());
            // 开启监听
            ignoreTextChange = false;
        }

        // update 已有的 aitBlock
        atModel.onInsertText(start, content);

        int index = needInsertAitInText ? start : start - 1;
        // 添加当前到 aitBlock
        atModel.addAtUser(account, name, index);
    }

    /**
     * 当删除尾部空格时，删除一整个segment,包含界面上也删除.
     *
     * @param start
     * @param count
     * @return
     */
    private boolean deleteSegment(int start, int count) {
        if (count != 1) {
            return false;
        }
        boolean result = false;
        AtBlock.AtSegment segment = atModel.findAtSegmentByEndPos(start);
        if (segment != null) {
            int length = start - segment.start;
            if (listener != null) {
                ignoreTextChange = true;
                listener.onTextDelete(segment.start, length);
                ignoreTextChange = false;
            }
            atModel.onDeleteText(start, length);
            result = true;
        }
        return result;
    }

    /**
     *
     *
     * @param editable 变化后的Editable
     * @param start    text 变化区块的起始index
     * @param count    text 变化区块的大小
     * @param delete   是否是删除
     */
    private void afterTextChanged(Editable editable, int start, int count, boolean delete) {
        curPos = delete ? start : count + start;
        if (ignoreTextChange) {
            return;
        }
        if (delete) {
            int before = start + count;
            if (deleteSegment(before, count)) {
                return;
            }
            atModel.onDeleteText(before, count);

        } else {
            if (count <= 0 || editable.length() < start + count) {
                return;
            }
            CharSequence s = editable.subSequence(start, start + count);
            if (s == null) {
                return;
            }
            if (s.toString().equals("@")) {
                // 显示@列表界面
                if (!TextUtils.isEmpty(gid)) {
                    showAtUserActivity(false);
//                    Intent i = IntentFactory.createTargetChooseActivityIntent(context
//                            , TargetSource.groupMember
//                            , null
//                            , null
//                            , null
//                            , TargetSourceFilterFactory.createTargetSourceFilterGroupMember4At(context)
//                            , null
//                            , gid);
//                    ActivityCompat.startActivityForResult((Activity) context, i, ActivityRequestCode.REQUEST_CODE_FOR_AT_TARGET_CHOOSE, null);
                }
            }
            atModel.onInsertText(start, s.toString());
        }
    }

    public void showAtUserActivity(boolean needInsertAitInText) {
        Intent i = IntentFactory.createTargetChooseActivityIntent(context
                , TargetSource.groupMember
                , null
                , null
                , null
                , TargetSourceFilterFactory.createTargetSourceFilterGroupMember4At(context)
                , Boolean.valueOf(needInsertAitInText)
                , gid);
        ActivityCompat.startActivityForResult((Activity) context, i, ActivityRequestCode.REQUEST_CODE_FOR_AT_TARGET_CHOOSE, null);
    }

    private int editTextStart;
    private int editTextCount;
    private int editTextBefore;
    private boolean delete;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        delete = count > after;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        this.editTextStart = start;
        this.editTextCount = count;
        this.editTextBefore = before;
    }

    @Override
    public void afterTextChanged(Editable s) {
        afterTextChanged(s, editTextStart, delete ? editTextBefore : editTextCount, delete);
    }

    public interface AtTextChangeListener {

        void onTextAdd(String content, int start, int length);

        void onTextDelete(int start, int length);
    }
}
